﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace Office365Log
{
    public static class LogManager
    {
        public static void LogError(Exception ex)
        {
            LogError(ex, null, "");
        }

        public static void LogError(Exception ex, string customMessage)
        {
            LogError(ex, null, customMessage);
        }

        public static void LogError(Exception ex, List<string> parameters)
        {
            LogError(ex, parameters, "");
        }

        public static void LogError(string customMessage)
        {
            LogError(new Exception(customMessage));
        }

        public static void LogError(Exception ex, List<string> parameters, string customMessage)
        {
            try
            {
                using (SPWeb curWeb = SPContext.Current.Web)
                {
                    SPList appLogList = curWeb.Lists["Application Log"];
                    SPListItem newItem = appLogList.AddItem();
                    newItem["Title"] = "View Item";

                    if (ex != null)
                    {
                        newItem["StackTrace"] = ex.StackTrace;
                        newItem["Exception"] = ex.Message;
                    }

                    if(ex.InnerException != null)
                        newItem["InnerException"] = ex.InnerException.Message;

                    System.Text.StringBuilder sb = new StringBuilder();
                    foreach (string parameter in parameters)
                    {
                        sb.AppendLine(parameter);
                    }
                    newItem["Parameters"] = sb.ToString();
                    newItem["CustomMessage"] = customMessage;
                    newItem["Username"] = curWeb.CurrentUser;
                    newItem.Update();
                }
            }
            catch { }
        }
    }
}
